package www.rlicker.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ActionFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		  HttpServletRequest request = (HttpServletRequest) servletRequest;
	      HttpServletResponse response = (HttpServletResponse) servletResponse;
		  String url = request.getRequestURI();
		  System.out.println(url);
		  if(url.indexOf("/login") > 1 || url.indexOf(".") > 1 || url.indexOf(".css") > 1 || url.indexOf(".js") > 1 || url.indexOf(".jpg") > 1 || url.indexOf(".png") > 1 || url.indexOf("/userlogin") >1){
			  chain.doFilter(request, response);
			  return;
		  }
		  Object session = request.getSession(true).getAttribute("user");
		  if(session == null){
			  url =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+ "/system/login";
			  response.sendRedirect(url);
			  return;
		  }else {
			  if (url.equals("/rlicker-app/")) {
				  url =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+ "/system/login";
				  response.sendRedirect(url);
				  return;
			  }
          }
		  chain.doFilter(request, response);
	}


	@Override
	public void destroy() {
		
	}

}
